# coding: utf-8

from __future__ import absolute_import, division, print_function, unicode_literals

import logging
import logging.config
import os
from datetime import datetime
from pathlib import Path

import bytedlogger
import six

from apitest import main_repo
from apitest.engine.const.constant import *


class LogIdFilter(logging.Filter):
    def filter(self, record):
        logid = getattr(record, "tags", {}).get("_logid")
        if logid:
            record._logid = logid
            return True
        logid = bytedlogger.thread_storage.get(b"_logid", "-")
        record._logid = six.ensure_text(logid)
        return True


class EnvFilter(logging.Filter):
    def filter(self, record):

        idc = getattr(record, "tags", {}).get("_logid")
        if idc:
            record._idc = idc
            return True
        env_tag = getattr(record, "tags", {}).get("_env_tag")
        if env_tag:
            record._env_tag = env_tag
            return True
        record._idc = os.environ.get(IDC_KEY)
        record._env_tag = os.getenv(ENV_LABEL_KEY)
        return True


def config_default(use_background=True):
    runtime_env = os.getenv("runtime_env")
    log_agent_version = os.getenv(LOG_AGENT_VERSION, "v1")
    level = os.getenv(LOG_LEVEL, "INFO")
    if log_agent_version == "v3":
        log_agent_handler = "log_agent_v3"
    elif log_agent_version == "v1":
        log_agent_handler = "log_agent"
    else:
        raise ValueError("invalid value for argument 'log_agent_version'")
    handlers = [log_agent_handler, "console"]
    if runtime_env != "tesla":
        handlers.append("log_file")

    runtime_logdir = Path(main_repo) / Path("log")
    runtime_logdir.mkdir(exist_ok=True)

    time = datetime.now().strftime("%Y%m%d")
    log_file = os.path.join(runtime_logdir, f"{time}.log")

    logging.config.dictConfig(
        {
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": {
                "default": {
                    "format": "%(asctime)s %(name)s %(levelname)s %(filename)s:%(lineno)d %(_logid)s %(message)s"
                }
            },
            "filters": {
                "logid_filter": {
                    "()": LogIdFilter,
                },
                "env_filter": {
                    "()": EnvFilter,
                }
            },
            "handlers": {
                "log_agent": {
                    "level": "INFO",
                    "class": "bytedlogger.StreamLogHandler",
                    "version": 1,
                    "tags": {},
                    "filters": ["logid_filter", "env_filter"],
                    "background": use_background,
                },
                "log_agent_v3": {
                    "level": "INFO",
                    "class": "bytedlogger.StreamLogHandler",
                    "version": 3,
                    "tags": {},
                    "filters": ["logid_filter", "env_filter"],
                    "background": use_background,
                },
                "console": {
                    "level": level,
                    "class": "logging.StreamHandler",
                    "formatter": "default",
                    "filters": ["logid_filter", "env_filter"],
                },
                "log_file": {
                    "level": "INFO",
                    "class": "logging.handlers.WatchedFileHandler",
                    "filename": log_file,
                    "formatter": "default",
                    "filters": ["logid_filter", "env_filter"],
                }
            },
            "root": {"handlers": handlers, "level": level},
            "loggers": {
                "apitest.engine.logging": {
                    "handlers": handlers,
                    "level": "INFO",
                    "propagate": True,
                },
            }
        }
    )


config_default()
logger = logging.getLogger(__name__)
